﻿namespace OneWorks.Utils.Export
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;

    public abstract class BaseExportFile<T> : IExportFile
    {
        protected string SavePath;
        protected List<T> Datas;
        protected string FileType;
        protected string FilePath;
        protected Dictionary<PropertyInfo, ExportAttribute> ProDictionary;
        protected List<string> FileTypeList = new List<string>
        {
            ".xls"
        };

        protected BaseExportFile(List<T> datas, string savePath)
        {
            Datas = datas;
            SavePath = savePath;
        }
        
        /// <summary>
        /// 验证文件类型
        /// </summary>
        protected void VerifyFileType()
        {
            if (FileTypeList.Any(c => c != FileType)) throw new ArgumentNullException();
        }

        /// <summary>
        /// 验证数据
        /// </summary>
        protected void VerifyData()
        {
            if (Datas == null) throw new ArgumentNullException();
        }

        /// <summary>
        /// 解析出上传文件类型与路径
        /// </summary>
        protected void ResolveFile()
        {
            FileType = Path.GetExtension(SavePath);
            FilePath = Path.GetFullPath(SavePath);
        }

        /// <summary>
        /// 获取实体属性标签，放入字典
        /// </summary>
        /// <returns></returns>
        protected Dictionary<PropertyInfo, ExportAttribute> GetDictionary()
        {
            Dictionary<PropertyInfo, ExportAttribute>  dictionary = new Dictionary<PropertyInfo, ExportAttribute>();
            foreach (PropertyInfo property in typeof(T).GetProperties())
            {
                var custAttributes = property.GetCustomAttributes(false);
                foreach (ExportAttribute attribute in custAttributes.Select(custAttribute => custAttribute as ExportAttribute))
                {
                    dictionary.Add(property, attribute ?? new ExportAttribute(property.Name,typeof(string)));
                }               
            }
            return dictionary;
        }

        public abstract string ToExport();
    }
}
